﻿Imports System.Security.Cryptography
Imports System.Text
Imports DTO
Imports BUS

Public Class FormDangNhap
    Public _flag As Integer = 0
    Public _loaiTK As Integer = 3
    Public _tenTK As String
    Dim _taiKhoanBUS As New TaiKhoanBUS()



    Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click
        Me.Close()
    End Sub

    Private Sub btnDangNhap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDangNhap.Click
        Dim _hashMK As String = getMd5Hash(txtMatKhau.Text)
        Dim _taiKhoanDTO As New TaiKhoanDTO(txtTenDangNhap.Text, _hashMK, Nothing)
        If (_taiKhoanBUS.KiemTraTKVaMKDAO(_taiKhoanDTO) = True) Then
            _taiKhoanDTO.LoaiTK = _taiKhoanBUS.GetLoaiTKBUS(_taiKhoanDTO)
            _flag = 1
            _loaiTK = _taiKhoanDTO.LoaiTK
            _tenTK = txtTenDangNhap.Text
            MessageBox.Show("Đăng nhập thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        Else
            MessageBox.Show("Kiểm tra lại tên đăng nhập hoặc mật khẩu")
        End If


    End Sub

    Function getMd5Hash(ByVal input As String) As String
        ' Create a new instance of the MD5 object.
        Dim md5Hasher As MD5 = MD5.Create()

        ' Convert the input string to a byte array and compute the hash.
        Dim data As Byte() = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input))

        ' Create a new Stringbuilder to collect the bytes
        ' and create a string.
        Dim sBuilder As New StringBuilder()

        ' Loop through each byte of the hashed data 
        ' and format each one as a hexadecimal string.
        Dim i As Integer
        For i = 0 To data.Length - 1
            sBuilder.Append(data(i).ToString("x2"))
        Next i

        ' Return the hexadecimal string.
        Return sBuilder.ToString()

    End Function


    Private Sub txtMatKhau_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtMatKhau.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            btnDangNhap_Click(Nothing, Nothing)
        End If
    End Sub

    Private Sub txtTenDangNhap_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtTenDangNhap.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            btnDangNhap_Click(Nothing, Nothing)
        End If
    End Sub
End Class